<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="基本概念多线程fork/join:fork join框架一个巨大的优势是它使用了工作窃取算法，可以完成更多任务的工作线程可以从其它线程中窃取任务来执行 多线程的几种实现方式 thread runnable threadpool Vector, SimpleDateFormat 是线程安全类吗SimpleDateFormat非安全，每次用都去new，因为里面用了Calendar，跟本地时区有关 哪些">
<meta property="og:type" content="article">
<meta property="og:title" content="技术问答2">
<meta property="og:url" content="http://yoursite.com/2017/07/14/java/技术问答2/index.html">
<meta property="og:site_name" content="Tissan">
<meta property="og:description" content="基本概念多线程fork/join:fork join框架一个巨大的优势是它使用了工作窃取算法，可以完成更多任务的工作线程可以从其它线程中窃取任务来执行 多线程的几种实现方式 thread runnable threadpool Vector, SimpleDateFormat 是线程安全类吗SimpleDateFormat非安全，每次用都去new，因为里面用了Calendar，跟本地时区有关 哪些">
<meta property="og:updated_time" content="2017-12-15T14:19:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="技术问答2">
<meta name="twitter:description" content="基本概念多线程fork/join:fork join框架一个巨大的优势是它使用了工作窃取算法，可以完成更多任务的工作线程可以从其它线程中窃取任务来执行 多线程的几种实现方式 thread runnable threadpool Vector, SimpleDateFormat 是线程安全类吗SimpleDateFormat非安全，每次用都去new，因为里面用了Calendar，跟本地时区有关 哪些">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: 'Java程序员'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/07/14/java/技术问答2/"/>





  <title>技术问答2 | Tissan</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tissan</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/07/14/java/技术问答2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="罗天翔">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tissan">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">技术问答2</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-14T21:12:09+08:00">
                2017-07-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/07/14/java/技术问答2/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/07/14/java/技术问答2/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2017/07/14/java/技术问答2/" class="leancloud_visitors" data-flag-title="技术问答2">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h3><h4 id="多线程"><a href="#多线程" class="headerlink" title="多线程"></a>多线程</h4><p>fork/join:fork join框架一个巨大的优势是它使用了工作窃取算法，可以完成更多任务的工作线程可以从其它线程中窃取任务来执行</p>
<p>多线程的几种实现方式 thread runnable threadpool</p>
<p>Vector, SimpleDateFormat 是线程安全类吗<br>SimpleDateFormat非安全，每次用都去new，因为里面用了Calendar，跟本地时区有关</p>
<p>哪些集合类是线程安全的 Stack Vector</p>
<p>多线程中的忙循环是什么:循环让线程等待，不会释放cpu，因为释放cpu要cpu缓存重建</p>
<p>线程和进程有什么区别？进程间如何通讯，线程间如何通讯<br>什么是多线程环境下的伪共享（false sharing）<br>同步和异步有何异同，在什么情况下分别使用他们？举例说明</p>
<p>ConcurrentHashMap 和 Hashtable的区别<br>ArrayBlockingQueue, CountDownLatch的用法</p>
<p>ConcurrentHashMap的并发度是什么<br>CyclicBarrier 和 CountDownLatch有什么不同？各自的内部原理和用法是什么<br>CyclicBarrier:<br>(1)构造函数提供，runnbale方法<br>(2)reset<br>(3)CyclicBarrier把线程都阻塞到一个地方，然后执行runnable方法，然后执行接下来的方法</p>
<p>Semaphore的用法 :信号量</p>
<p>yield方法有什么作用？sleep() 方法和 yield() 方法有什么区别<br>yield会暂停当前线程，然后让相同等级的线程先执行，如果其他线程优先级低，依旧当前线程执行</p>
<p>Java 中如何停止一个线程 interrupt等线程执行完<br>stop() 和 suspend() 方法为何不推荐使用<br>stop强行中断不管是否执行完，不安全<br>suspend会造成死锁，竞争资源，A获取锁调用suspend，B等待锁调用resume，然后A一直死锁</p>
<p>如何在两个线程间共享数据</p>
<p>如何让正在运行的线程暂停一段时间</p>
<p>你是如何调用 wait（方法的）？使用 if 块还是循环？为什么</p>
<p>有哪些不同的线程生命周期<br>线程状态，BLOCKED 和 WAITING 有什么区别<br>画一个线程的生命周期状态图<br>new<br>runnable<br>block<br>wait<br>ThreadLocal 用途是什么，原理是什么，用的时候要注意什么:<br>map(this.thread,value)<br>所有线程公用一个map，map的key是当前线程<br>ThreadLocal可以让SimpleDateFormat变得线程安全</p>
<p>FutureTask:可取消的异步计算cancel,获取计算返回的值get</p>
<p>线程池是什么？为什么要使用它<br>如何创建一个Java线程池<br>提交任务时，线程池队列已满时会发会生什么：任务放弃执行<br>newCache 和 newFixed 有什么区别？简述原理。构造函数的各个参数的含义是什么，比如 coreSize, maxsize 等<br>newCache:线程可以增多<br>newFixed:有最大的线程</p>
<p>线程池的实现策略:<br><a href="http://www.infoq.com/cn/articles/java-threadPool" target="_blank" rel="external">http://www.infoq.com/cn/articles/java-threadPool</a><br>线程池的关闭方式有几种，各自的区别是什么 shutdown shutdownNow<br>线程池中submit() 和 execute()方法有什么区别？ submit可接受异常  execute不可以<br>线程调度<br>线程数配置:<br>(1)CPU密集:线程数配置少些,N+1,这样保证都在同一个cpu上执行<br>(2)IO密集:就可以多配置一些线程,2N,这样能保证CPU被充分利用</p>
<p>Java中用到的线程调度算法是什么<br>什么是多线程中的上下文切换<br>你对线程优先级的理解是什么<br>什么是线程调度器 (Thread Scheduler) 和时间分片 (Time Slicing)<br>线程同步</p>
<p>序列化一个对象:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">People people = <span class="keyword">new</span> People();</div><div class="line">        people.setName(<span class="string">"luo"</span>);</div><div class="line">        people.setAge(<span class="number">10</span>);</div><div class="line"></div><div class="line">        FileOutputStream fileOutputStream = <span class="keyword">null</span>;</div><div class="line">        ObjectOutputStream objectOutputStream = <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            fileOutputStream = <span class="keyword">new</span> FileOutputStream(<span class="string">"people.txt"</span>);</div><div class="line">            objectOutputStream = <span class="keyword">new</span> ObjectOutputStream(fileOutputStream);</div><div class="line">            objectOutputStream.writeObject(people);</div><div class="line">        &#125; <span class="keyword">catch</span> (FileNotFoundException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125; <span class="keyword">finally</span> &#123;</div><div class="line">            objectOutputStream.close();</div><div class="line">            objectOutputStream.flush();</div><div class="line">            fileOutputStream.close();</div><div class="line">        &#125;</div><div class="line"></div><div class="line"></div><div class="line">        FileInputStream fileInputStream = <span class="keyword">null</span>;</div><div class="line">        ObjectInputStream objectInputStream = <span class="keyword">null</span>;</div><div class="line"></div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            fileInputStream = <span class="keyword">new</span> FileInputStream(<span class="string">"people.txt"</span>);</div><div class="line">            objectInputStream = <span class="keyword">new</span> ObjectInputStream(fileInputStream);</div><div class="line">            People people1 = (People) objectInputStream.readObject();</div><div class="line">            System.out.println(people1.toString());</div><div class="line">        &#125; <span class="keyword">catch</span> (ClassNotFoundException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div></pre></td></tr></table></figure></p>
<p>synchronized 的原理是什么<br>synchronized 和 ReentrantLock 有什么不同<br>什么场景下可以使用 volatile 替换 synchronized<br>有T1，T2，T3三个线程，怎么确保它们按顺序执行？怎样保证T2在T1执行完后执行，T3在T2执行完后执行<br>同步块内的线程抛出异常会发生什么<br>当一个线程进入一个对象的 synchronized 方法A 之后，其它线程是否可进入此对象的 synchronized 方法B<br>使用 synchronized 修饰静态方法和非静态方法有什么区别<br>如何从给定集合那里创建一个 synchronized 的集合</p>
<p>Java Concurrency API 中 的 Lock 接口是什么？对比同步它有什么优势<br>Lock 与 Synchronized 的区别？Lock 接口比 synchronized 块的优势是什么<br>ReadWriteLock是什么？//读锁可以并发读，但是上了写锁<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">final</span> ReadWriteLock readWriteLock = <span class="keyword">new</span> ReentrantReadWriteLock();</div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">30</span>; i++) &#123;</div><div class="line">            <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                    readWriteLock.readLock().lock();</div><div class="line">                    <span class="keyword">try</span> &#123;</div><div class="line">                        Thread.sleep(<span class="number">500</span>);</div><div class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">                        e.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                    System.out.println(<span class="string">"-----"</span>+Thread.currentThread().getName());</div><div class="line">                    readWriteLock.readLock().unlock();</div><div class="line">                &#125;</div><div class="line">            &#125;).start();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            Thread.sleep(<span class="number">3000</span>);</div><div class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</div><div class="line">            <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                    readWriteLock.writeLock().lock();</div><div class="line">                    <span class="keyword">try</span> &#123;</div><div class="line">                        Thread.sleep(<span class="number">500</span>);</div><div class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">                        e.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                    System.out.println(<span class="string">"--aaa---"</span>+Thread.currentThread().getName());</div><div class="line">                    readWriteLock.writeLock().unlock();</div><div class="line">                &#125;</div><div class="line">            &#125;).start();</div><div class="line">        &#125;</div><div class="line"></div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>锁机制有什么用<br>什么是乐观锁（Optimistic Locking）？如何实现乐观锁？如何避免ABA问题<br>解释以下名词：重排序，自旋锁，偏向锁，轻量级锁，可重入锁，公平锁，非公平锁，乐观锁，悲观锁<br>什么时候应该使用可重入锁<br>简述锁的等级方法锁、对象锁、类锁<br>Java中活锁和死锁有什么区别？<br>什么是死锁(Deadlock)？导致线程死锁的原因？如何确保 N 个线程可以访问 N 个资源同时又不导致死锁<br>死锁与活锁的区别，死锁与饥饿的区别<br>怎么检测一个线程是否拥有锁:<br>final Object obj = new Object();<br>        for (int i = 0; i &lt; 4; i++) {<br>            new Thread(new Runnable() {<br>                @Override<br>                public void run() {<br>                    //如果大家都是一起获取到锁，过了1秒都执行—–<br>                    //因为要等待获取锁，所以每个都要等到1秒执行<br>                    synchronized (obj) {<br>                        try {<br>                            Thread.sleep(1000);<br>                        } catch (InterruptedException e) {<br>                            e.printStackTrace();<br>                        }<br>                        System.out.println(“—–”);<br>                    }<br>                }<br>            }).start();<br>        }</p>
<p>线程间通信：synchronized wait/notify</p>
<p>如何实现分布式锁:zookeeper分布式锁，redis分布式锁</p>
<p>有哪些无锁数据结构，他们实现的原理是什么  ConcurrentLinkedQueue 节点队列，FIFO</p>
<p>线程池:ThreadPoolExecutor<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">new</span> RejectedExecutionHandler() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rejectedExecution</span><span class="params">(Runnable r, ThreadPoolExecutor executor)</span> </span>&#123;</div><div class="line">            <span class="keyword">if</span> (!executor.isShutdown()) &#123;</div><div class="line">                <span class="keyword">try</span> &#123;</div><div class="line">                    executor.getQueue().put(r);</div><div class="line">                    <span class="comment">//put会阻塞</span></div><div class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line"></div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>Executors类是什么？ Executor和Executors的区别<br>Executor是线程池的顶级父类，我们重写他的execute方法<br>Executors是创建线程池的方法</p>
<p>什么是Java线程转储(Thread Dump)，如何得到它:<br>如何在Java中获取线程堆栈<br>说出 3 条在 Java 中使用线程的最佳实践<br>1.线程池<br>在线程中你怎么处理不可捕捉异常<br>实际项目中使用多线程举例。你在多线程环境中遇到的常见的问题是什么？你是怎么解决它的<br>请说出与线程同步以及线程调度相关的方法<br>程序中有3个 socket，需要多少个线程来处理<br>假如有一个第三方接口，有很多个线程去调用获取数据，现在规定每秒钟最多有 10 个线程同时调用它，如何做到<br>如何在 Windows 和 Linux 上查找哪个线程使用的 CPU 时间最长<br>如何确保 main() 方法所在的线程是 Java 程序最后结束的线程<br>非常多个线程（可能是不同机器），相互之间需要等待协调才能完成某种工作，问怎么设计这种协调方案<br>你需要实现一个高效的缓存，它允许多个用户读，但只允许一个用户写，以此来保持它的完整性，你会怎样去实现它</p>
<p>Error 和 Exception有什么区别<br>Error是个很严重的问题，没必要catch必要拿出解决<br>Exception可能想要捕获的条件</p>
<p>UnsupportedOperationException是什么<br>NullPointerException 和 ArrayIndexOutOfBoundException 之间有什么相同之处<br>运行时异常与一般异常有何异同<br>finally</p>
<p>finally关键词在异常处理中如何使用<br>如果执行finally代码块之前方法返回了结果，或者JVM退出了，finally块中的代码还会执行吗<br>try里有return，finally还执行么？那么紧跟在这个try后的finally {}里的code会不会被执行，什么时候被执行，在return前还是后<br>在什么情况下，finally语句不会执行<br>OOM你遇到过哪些情况？你是怎么搞定的？<br>SOF你遇到过哪些情况？  递归</p>
<p>既然我们可以用RuntimeException来处理错误，那么你认为为什么Java中还存在检查型异常<br>FileNotFoundException:<br>Unchecked Exception:NullPointerException编译器不会强制trycatch代码</p>
<p>导致空指针异常的原因<br>异常处理 handle or declare 原则应该如何理解</p>
<p>你曾经自定义实现过异常吗？怎么写的<br>Exception的父类Throwable，他的构造函数是<br>public Throwable(String message) {<br>        fillInStackTrace();<br>        detailMessage = message;<br>}<br>阐述 JDBC 操作数据库的基本步骤</p>
<p>使用 JDBC 操作数据库时，如何提升读取数据的性能？如何提升更新数据的性能</p>
<p>列出 5 个应该遵循的 JDBC 最佳实践<br>有很多的最佳实践，你可以根据你的喜好来例举。下面是一些更通用的原则：<br>a）使用批量的操作来插入和更新数据<br>b）使用 PreparedStatement 来避免 SQL 异常，并提高性能。<br>c）使用数据库连接池<br>d）通过列名来获取结果集，不要使用列的下标来获取。</p>
<p>为了提高读写性能，可以采用什么流:字符流</p>
<p>Java中有几种类型的流</p>
<p>JDK 为每种类型的流提供了一些抽象类以供继承，分别是哪些类</p>
<p>对文本文件操作用什么I/O流：</p>
<p>对各种基本数据类型和String类型的读写，采用什么流</p>
<p>能指定字符编码的 I/O 流类型是什么</p>
<p>什么是序列化？如何实现 Java 序列化及注意事项</p>
<p>Serializable 与 Externalizable 的区别</p>
<p>socket 选项 TCP NO DELAY 是指什么<br>Socket 工作在 TCP/IP 协议栈是哪一层：<br>TCP、UDP 区别及 Java 实现方式<br>说几点 IO 的最佳实践<br>直接缓冲区与非直接缓冲器有什么区别？<br>怎么读写 ByteBuffer？ByteBuffer 中的字节序是什么<br>当用System.in.read(buffer)从键盘输入一行n个字符后，存储在缓冲区buffer中的字节数是多少<br>如何使用扫描器类（Scanner Class）令牌化<br>面向对象编程（OOP）<br>解释下多态性（polymorphism），封装性（encapsulation），内聚（cohesion）以及耦合（coupling）<br>多态的实现原理<br>封装、继承和多态是什么<br>对象封装的原则是什么?<br>类<br>获得一个类的类对象有哪些方式<br>重载（Overload）和重写（Override）的区别。重载的方法能否根据返回类型进行区分？<br>说出几条 Java 中方法重载的最佳实践<br>抽象类<br>抽象类和接口的区别<br>抽象类中是否可以有静态的main方法<br>抽象类是否可实现(implements)接口<br>抽象类是否可继承具体类(concrete class)<br>匿名类（Anonymous Inner Class）<br>匿名内部类是否可以继承其它类？是否可以实现接口</p>
<p>内部类分为几种<br>内部类可以引用它的包含类（外部类）的成员吗<br>请说一下 Java 中为什么要引入内部类？还有匿名内部类</p>
<p>继承（Inheritance）与聚合（Aggregation）的区别在哪里</p>
<p>存在两个类，B 继承 A，C 继承 B，能将 B 转换为 C 么？如 C = (C) B</p>
<p>如果类 a 继承类 b，实现接口c，而类 b 和接口 c 中定义了同名变量，请问会出现什么问题</p>
<p>如何在Java中获取日历类的实例</p>
<p>解释一些日历类中的重要方法</p>
<p>GregorianCalendar 类是什么</p>
<p>SimpleTimeZone 类是什么</p>
<p>Locale类是什么</p>
<p>如何添加小时(hour)到一个日期对象(Date Objects)</p>
<p>如何将字符串 YYYYMMDD 转换为日期</p>
<p>Math.round()什么作用？Math.round(11.5) 等于多少？Math.round(-11.5)等于多少？</p>
<p>Class.forName<br>ClassLoader</p>
<p>Java解析XML的方式<br>用 jdom 解析 xml 文件时如何解决中文问题？如何解析<br>你在项目中用到了 XML 技术的哪些方面？如何实现<br>动态代理<br>描述动态代理的几种实现方式，分别说出相应的优缺点</p>
<p>线程状态：<br>New:线程还没有调用start方法<br>Runnable:线程正在执行<br>Blocked:线程阻塞等待获取锁<br>waiting:等待其他线程操作 object.wait Thread.join<br>time_waiting:线程等待特定的时间 Thread.sleep<br>terminated:方法退出<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">Thread.currentThread().setName(<span class="string">"thread-66"</span>);</div><div class="line">        Thread thread2 = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                Thread.currentThread().setName(<span class="string">"thread-77"</span>);</div><div class="line">                run0();</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">        thread2.start();</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            Thread.sleep(<span class="number">1000</span>);</div><div class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">        run0();</div><div class="line">        System.out.println(<span class="string">"-----"</span>);</div></pre></td></tr></table></figure></p>
<p>设计模式<br>什么是设计模式（Design Patterns）？你用过哪种设计模式？用在什么场合<br>你知道哪些商业级设计模式？<br>哪些设计模式可以增加系统的可扩展性<br>单例模式<br>除了单例模式，你在生产环境中还用过什么设计模式？<br>写 Singleton 单例模式<br>单例模式的双检锁是什么<br>如何创建线程安全的 Singleton<br>什么是类的单例模式<br>写出三种单例模式实现<br>适配器模式<br>适配器模式是什么？什么时候使用<br>适配器模式和代理模式之前有什么不同<br>适配器模式和装饰器模式有什么区别<br>什么时候使用享元模式<br>什么时候使用组合模式<br>什么时候使用访问者模式<br>什么是模板方法模式<br>请给出1个符合开闭原则的设计模式的例子</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/uploads/wechat.png" alt="罗天翔 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/uploads/ali.jpg" alt="罗天翔 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/07/14/rocketmq/Producer发送消息/" rel="next" title="Producer发送消息">
                <i class="fa fa-chevron-left"></i> Producer发送消息
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/14/java/重写hashcode和equals/" rel="prev" title="重写hashcode 和 equals">
                重写hashcode 和 equals <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="罗天翔" />
          <p class="site-author-name" itemprop="name">罗天翔</p>
           
              <p class="site-description motion-element" itemprop="description">一次就把事情做对.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">73</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/louiegit/" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="" target="_blank" title="微信">
                  
                    <i class="fa fa-fw fa-wechat"></i>
                  
                  微信
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本概念"><span class="nav-number">1.</span> <span class="nav-text">基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#多线程"><span class="nav-number">1.1.</span> <span class="nav-text">多线程</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">罗天翔</span>
</div>


<div class="powered-by">
  NBA & Code. What?
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyt9ceIwz';
      var conf = 'c6226e2bfb7e9c65efc235736edc5074';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  




  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("PITM8mBWsQN3SJFbzhc4ENjF-gzGzoHsz", "XDe54bE6K2j8dN2EzXkB7NzE");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
